package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.NoticeDao;
import dao.UsersDao;
import dao.impl.NoticeDaoImpl;
import dao.impl.UsersDaoImpl;
import entity.Notice;
import entity.Users;
import utils.GetFieldUtils;
import utils.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "NoticeServlet", urlPatterns = "/bigProjects/NoticeServlet")

public class NoticeServlet extends HttpServlet {

    //获取最新公告 (无参数)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NoticeDao noticeDao = new NoticeDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        Notice notice = noticeDao.queryNewNotice();
        resp.getWriter().write(ResponseResult.success(notice).toString());
    }

    //获取所有公告
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NoticeDao noticeDao = new NoticeDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        List<Notice> noticeData = noticeDao.getAllNotices();
        resp.getWriter().write(ResponseResult.success(noticeData).toString());
    }

    //新增留言
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NoticeDao noticeDao = new NoticeDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String str = GetFieldUtils.getRequestPayload(req);
        ObjectMapper mapper = new ObjectMapper();
        //读取前端传递的Json字符串,转成Users对象
        Notice notice = mapper.readValue(str, Notice.class);
        int i = noticeDao.insert(notice);
        if (i > 0) resp.getWriter().write(ResponseResult.success().toString());
        else resp.getWriter().write(ResponseResult.failure("新增失败").toString());
    }
}
